<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'main';
cfc('core')->checklogin('jy_jdpm/member.index/');
$return=array();
set_html('title','订单中心');
if($_RQ['op']=='main'){
	$id=$_RQ['order_no'];
	if(!$id){
		exi('请先选择订单！','error','goback');
	}
	$order=pdo_get('jy_jdpm_order',array('order_no'=>$id),array('pid','mid','price','order_no','freight','commission','service_fees','margin','status'));
	$order['address']=json_decode($order['address'],true);
	$aution=pdo_get('jy_jdpm_auction',array('id'=>$order['pid']),array('pid','goodsid'));
	$goods=pdo_get('jy_jdpm_goods',array('id'=>$aution['goodsid']),array('id','title','images'));
	$goods_user=pdo_get('jy_jdpm_freezelog',array('mid'=>$order['mid'],'pid'=>$order['pid'],'status'=>0),array('pledge'));
	$ad=pdo_getall('core_address',array('mid'=>$order['mid']),array('adid','prov','city','district','provaddress','address','truename','mobile'));
	$item=array_merge($order,$aution,$goods,$goods_user,$ad);
	$item['image'] =explode('|',$goods['images'])[0];
	$item['price_freight']=$item['price']+$item['freight'];
	$item['res_price']=$item['price_freight']-$item['pledge'];
	$item['adid']=$order['address']['adid'];
	$item['statustitle'] = $this->ordertypes()[$item['status']];
	$return['info']=$item;
	$return['address']=$ad;
	exi($return);
}
if($_RQ['op']=='post'){
	//支付订单
	$post=get_postdata();
	$id=$post['order_no'];
	$Password = pdo_getcolumn('jy_jdpm_member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid']),'paypwd');
	if(empty($Password)){
		  confirm('您还没有设置支付密码，请先设置支付密码','jy_jdpm/member.safety/setpay/');
	}
	if(encryptPwd($post['password']) != $Password){
		 exi('支付密码错误！','error');
	}
	if(!$id){
		exi('请先选择订单！','error');
	}
	if(!$post['adid']){
		exi('请先选择收货地址！','error');
	}
	$order=pdo_get('jy_jdpm_order',array('order_no'=>$id));
	if(!$order){
		exi('订单不存在！','error');
	}
	if($order['status']==-1){
		exi('订单已逾期！','error');
	}
	if($order['status']){
		exi('订单已支付！','error');
	}
	$ad=pdo_get('core_address',array('adid'=>$post['adid']));
	$address=array('provaddress'=>$ad['provaddress'],'truename'=>$ad['truename'],'mobile'=>$ad['mobile'],'address'=>$ad['address']);
$Balance = pdo_get('jy_jdpm_member',array('mid'=>$_SESSION['uid']),array('wallet_pledge','wallet_pledge_freeze','brokerage'));
$member=get_member($_SESSION['uid'])
$Balance['balance']=$member['credit2'];
$Balance['freeze']=$Balance['wallet_pledge_freeze'];
$UserList=pdo_getall('jy_jdpm_freezelog',array('uniacid'=>$_SESSION['uniacid'],'pid'=>$order['pid'],'status'=>1),array('mid','createtime'));
//成交价
$PlayMoney = $order['price'];
$money=$Balance['balance'] - $Balance['freeze'] - $order['price'] + $order['margin'];
if($money<0){
		exi('余额不足！请先充值！','error');
}
//起拍价
$onset = pdo_getcolumn('jy_jdpm_auction',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['pid']),'onset');
$Orderset=$this->plugin_setting('order');
//支付比例
$mid  = $Orderset['mid'] ? $Orderset['mid'] : 0.08;//（成交价-起拍价）×8%；比例：0.08
$merchid   = $Orderset['merchid'] ? $Orderset['merchid'] : 0.50;//起拍价+（成交价-起拍价）×50%-挂牌手续费-服务费；比例：0.5
$agent      = $Orderset['agent'] ? $Orderset['agent'] : 0.02;//(成交价-起拍价)×2%×有归属经纪人的用户有效竞拍次数/（总竞拍次数-1）;（成交人除外，不参与收益分配，如无推荐人归平台所有）。
$jpuser     = $Orderset['jpuser'] ? $Orderset['jpuser'] : 0.30;//（成交价-起拍价）×30%×该用户的有效竞拍次数/（总竞拍次数-1）；（成交人除外，不参与收益分配）。
$fuwufee     = $Orderset['fuwufee'] ? $Orderset['fuwufee'] : 0.01;//成交价×1%
$guapaifee     = $Orderset['guapaifee'] ? $Orderset['guapaifee'] : 0.02;//起拍价×2%
//服务费
$fuwufee = round($fuwufee*$PlayMoney,2);
//挂牌手续费
$guapaifee = round($guapaifee*$onset,2);
//送拍人所得
$merchfee = $onset + ($PlayMoney-$onset) * $merchid - $fuwufee - $guapaifee;//委托人所得保证金*20%
$merchfee = round($merchfee,2);
//送拍商所得
$midfee = ($PlayMoney-$onset) * $mid;
$midfee = round($midfee,2);
//平台所得（总减）
$systemfee   = $PlayMoney - $merchfee - $midfee - $fuwufee - $guapaifee;

if ($UserList) {
	$num    = count($UserList);
		foreach($UserList as $k=>$userv){
			//如果竞拍人不存在，剔除
			$inuid = pdo_getcolumn('jy_jdpm_member', array('mid' => $userv['mid']),'mid');
			if(empty($inuid)){
				unset($UserList[$k]);
			}
		}
			//竞买人：
			$jpuserfee = ($PlayMoney-$onset) * $jpuser/$num;
			$jpuserfee = round($jpuserfee,2);
			//经纪人：
			$agentfee  = ($PlayMoney-$onset) * $agent/$num;
			$agentfee = round($agentfee,2);
			//减出竞买人-平台所得
			$systemfee = $systemfee - ($jpuserfee*$num);
			$systemfee = round($systemfee,2);
}
		
		//首拍送积分
		$l1=pdo_getall('jy_jdpm_freezelog',array('pid'=>$order['pid']),array('mid'),'','time asc');
		if($l1){
			$set=$this->plugin_setting('basic');	
			$add=$set['firstend']?$set['firstend']:2;
			$add=floor($onset*$add)/100;
			
			pdo_insert('jy_jdpm_credit_log',array('mid'=>$l1[0]['mid'],'is_add'=>1,'type'=>4,'pid'=>$pid,'fee'=>$add,'remark'=>'首拍送积分','createtime'=>time()));
		}
		
		//尾拍积分
		$l=pdo_get('jy_jdpm_freezelog',array('uid <>'=>$_SESSION['uid'],'pid'=>$order['pid']));
		if($l){	
			$set=$this->plugin_setting('basic');
			$add=$set['firstend']?$set['firstend']:2;
			$add=floor($order['price']*$add)/100;
		
			pdo_insert('jy_jdpm_credit_log',array('mid'=>$_SESSION['uid'],'is_add'=>1,'type'=>4,'pid'=>$pid,'fee'=>$add,'remark'=>'尾拍送积分','createtime'=>time()));
		}
		//更改订单信息
            $OUpData = [
                'status'     => 1 ,
                'buyer_msg'  => $post['buyer_msg'] ,
                'time1'      => time() ,
                'defgetgoodstimest' => 0 ,
                'defgetgoodstime'   => TIMESTAMP + (24*3600*$Orderset['losetime1']) ,
                'address'    => ijson_encode($address) ,
            ];

            pdo_update('jy_jdpm_order',$OUpData,array('order_no'=>$order['order_no']));
			//更新拍品状态
			pdo_update('jy_jdpm_auction',array('endstatus'=>1),array('id'=>$order['pid']));
            //更改保证金状态
			pdo_update('jy_jdpm_freezelog',array('status'=>3,'rtime'=>TIMESTAMP),array('pid'=>$order['pid'],'status'=>0));

            if ($Balance['brokerage'] > $PlayMoney) {
                $Brokerage = $Balance['brokerage'] - $PlayMoney;
            }


            //扣除用户金额
            $MUpData = [
                'wallet_pledge'        => $Balance['balance'] - $PlayMoney ,
                'brokerage'            => ($Balance['brokerage'] > $PlayMoney) ? ($Balance['brokerage'] - $PlayMoney) : 0 ,
                'wallet_pledge_freeze' => $Balance['freeze'] - $order['margin'] ,
            ];
			pdo_update('jy_jdpm_member',$MUpData,array('mid'=>$_SESSION['uid']));
			pdo_update('core_members',array('credit2 -='=>$PlayMoney),array('id'=>$_SESSION['uid']));
            //卖家收入金额
			pdo_update('jy_jdpm_member',array('wallet_pledge +='=>$merchfee),array('mid'=>$order['merchid']));
			pdo_update('core_members',array('credit2 +='=>$merchfee),array('id'=>$order['merchid']));
			//送拍商收入金额
			pdo_update('jy_jdpm_member',array('wallet_pledge +='=>$midfee),array('mid'=>$order['mid']));
			pdo_update('core_members',array('credit2 +='=>$midfee),array('id'=>$order['mid']));

            $Log = [
                [   //买家
                    'mid'          => $order['mid'] ,
                    'money'        => $order['price'] ,
                    'channel'      => 2 ,
                    'create_time'  => time() ,
                    'update_time'  => time() ,
                    'auction_time' => 0 ,
                    'remarks'      => '支付拍品订单' ,
                    'type'         => 2 ,
                    'pid'          => $order['pid'] ,
                    'role'         => '成交人'
                ] ,
                [   //卖家
                    'mid'          => $order['merchid'] ,
                    'money'        => $merchfee ,
                    'channel'      => 1 ,
                    'create_time'  => time() ,
                    'update_time'  => time() ,
                    'auction_time' => 99999999999 ,
                    'remarks'      => '拍品收入' ,
                    'role'         => '送拍人' ,
                    'type'         => 4 ,
                    'pid'          => $order['pid']
                ] ,
				[   //送拍商
                    'mid'          => $order['mid'] ,
                    'money'        => $midfee ,
                    'channel'      => 1 ,
                    'create_time'  => time() ,
                    'update_time'  => time() ,
                    'auction_time' => 99999999999 ,
                    'remarks'      => '拍品收入' ,
                    'role'         => '送拍商' ,
                    'type'         => 4 ,
                    'pid'          => $order['pid']
                ] ,
                
                [   //服务费
                    'mid'          => -1 ,
                    'money'        => $fuwufee ,
                    'channel'      => 1 ,
                    'create_time'  => time() ,
                    'update_time'  => time() ,
                    'auction_time' => 2 ,
                    'remarks'      => '服务费收入' ,
                    'role'         => '广宝' ,
                    'type'         => 5 ,
                    'pid'          => $order['pid']
                ] ,
				
                [   //手续费
                    'mid'          => -2 ,
                    'money'        => $guapaifee ,
                    'channel'      => 1 ,
                    'create_time'  => time() ,
                    'update_time'  => time() ,
                    'auction_time' => 1 ,
                    'remarks'      => '手续费收入' ,
                    'role'         => '平台' ,
                    'type'         => 5 ,
                    'pid'          => $order['pid']
                ]
            ];
            //发放竞拍拥金
			$sharefee=0;
            if (!empty($UserList)) {
                foreach ($UserList AS $value) {
                    pdo_update('jy_jdpm_member',array('brokerage +='=>$jpuserfee,'wallet_pledge +='=>$jpuserfee),array('mid'=>$value['mid']));
                    pdo_update('core_members',array('credit2 +='=>$agentfee),array('id'=>$value['mid']));
					$Log[] = [
                        'mid'          => (int)$value['mid'] ,
                        'money'        => $jpuserfee ,
                        'channel'      => 1 ,
                        'create_time'  => time() ,
                        'update_time'  => time() ,
                        'auction_time' => (int)$value['createtime'] ,
                        'remarks'      => '竞拍奖励金收入' ,
						'role'         => '竞拍人',
                        'type'         => 3 ,
                        'pid'          => $order['pid']
                    ];
					$sourceuid = pdo_getcolumn('core_members',array('id'=>$value['mid']),'fromuser');
					//剔除不存在的经纪人
					$sourceinuid =	pdo_getcolumn('core_members',array('id'=>$sourceuid),'id');
					if($sourceuid && $sourceinuid){		
						//推广分享金
						pdo_update('jy_jdpm_member',array('brokerage +='=>$agentfee,'wallet_pledge +='=>$agentfee),array('mid'=>$sourceuid));
						pdo_update('core_members',array('credit2 +='=>$agentfee),array('id'=>$sourceuid));
						$Log[] = [
						
									'mid'          => $sourceuid ,
									'comuid'       => $value['mid'],
									'money'        => $agentfee ,
									'channel'      => 1 ,
									'create_time'  => time() ,
									'update_time'  => time() ,
									'auction_time' => 0 ,
									'remarks'      => '推广分享金收入' ,
									'role'         => '平台经纪人',
									'type'         => 7 ,
									'pid'          => $order['pid']
								];
						$sharefee +=$agentfee;
					}
                }
            }
			//保证金解冻-转出
			$mlog=array(
                        'mid'          => $order['mid'],
                        'money'        => $order['margin'] ,
                        'channel'      => 1 ,
                        'create_time'  => time()-1 ,
                        'update_time'  => time()-1 ,
                        'auction_time' => 0 ,
                        'remarks'      => '支付解冻' ,
						'role'         => '',
                        'type'         => 15 ,
						'pid'          => $order['pid']
                       
			);
			/*$userlog=array(
                        'mid'          => $order['mid'],
                        'pledge'        => $order['margin'] ,
                        'createtime'  => time()-1 ,
                        'status' => 2 ,
                        'remarks'      => '支付扣除' , 
			);*/
			$lg['uniacid']=$_SESSION['uniacid'];
			pdo_insert('jy_jdpm_money_log',$mlog);
			//pdo_insert('jy_jdpm_freezelog',$userlog);
			$Log[] = [   //平台
                    'mid'          => 0 ,
                    'money'        => $systemfee - $sharefee ,
                    'channel'      => 1 ,
                    'create_time'  => time() ,
                    'update_time'  => time() ,
                    'auction_time' => 0 ,
                    'remarks'      => '平台拍品收入' ,
                    'role'         => '平台佣金' ,
                    'type'         => 3 ,
                    'pid'          => $order['pid']
                ] ;
            $Log = $this->array_sort($Log , 'auction_time' , $type = 'asc');
            ksort($Log);
            foreach ($Log AS $value) {
                pdo_insert('jy_jdpm_money_log',$value);
            }
	exi('支付成功！','','member.index/');
}
